<?php
class ControllerStockStockIn extends Controller {
	private $error = array();
	
	//仓库初始化
	public function index() {
        $this->load->language('stock/stock_in');
		// var_dump($this->language->get('heading_title'));die();

		$this->document->setTitle($this->language->get('heading_title'));
		
		$this->load->model('stock/stock_in');

		$this->getList();

    }
	
		//获取仓库列表
	private function getList(){

	$page = I('get.page');
    if(!$page){
      $page = 1;
    }
    if($this->user->getLp()){
      //$filter['stock_in.user_id'] = $this->user->getId();
    }
    $data = I('get.');
    // var_dump($data);
    $this->document->addScript('view/javascript/angular.js');
    $this->document->addScript('view/javascript/bhz_ctl.js');
/*
    if(!empty($data['filter_date_start'])){
      $filter_date_start = $data['filter_date_start'];
    }else{
      $filter_date_start = '0000-00-00';
    }

    if(!empty($data['filter_date_end'])){
      $filter_date_end = $data['filter_date_end'];
    }else{
      $filter_date_end = '9999-12-31';
    }
    $filter['stock_in.date_added'] = array('between',array($filter_date_start,$filter_date_end));
*/
    /*
     * 修正分页后时间下拉框不能操作的异常
     * @author sonicsjh
     */
    if (!empty($data['filter_date_start']) && !empty($data['filter_date_end'])) {
        $filter_date_start = $data['filter_date_start'];
        $filter_date_end = $data['filter_date_end'];
        $filter['stock_in.date_added'] = array('between', array($filter_date_start.' 00:00:00', $filter_date_end.' 23:59:59'));
    }else if (!empty($data['filter_date_start'])) {
        $filter_date_start = $data['filter_date_start'];
        $filter['stock_in.date_added'] = array('gt', $filter_date_start.' 00:00:00');
    }else if (!empty($data['filter_date_end'])) {
        $filter_date_end = $data['filter_date_end'];
        $filter['stock_in.date_added'] = array('lt', $filter_date_end.' 23:59:59');
    }

    if(isset($data['warehouse_id'])){
      $warehouse_id = trim($data['warehouse_id']);
      if($warehouse_id!='*'){
      	$filter['w.warehouse_id'] = $warehouse_id;
      }  
    }else{
      $data['warehouse_id'] = '*';
    }

    if(isset($data['refer_type_id'])){
      $refer_type_id = trim($data['refer_type_id']);
      if($refer_type_id!='*'){
      	$filter['stock_in.refer_type_id'] = $refer_type_id;
      }  
    }else{
      $data['refer_type_id'] = '*';
    }

    if(!empty($data['username'])){
      $username = trim($data['username']);
      $filter['v.username'] = array('like',"%".$username."%");
    }
    if(!empty($data['in_id'])){
      $in_id = trim($data['in_id']);
      $filter['stock_in.in_id'] = array('like',"%".$in_id."%");
    }


    if(isset($data['filter_status'])){
      $filter_status = trim($data['filter_status']);
      if($filter_status!='*'){
        $filter['stock_in.status'] = $filter_status;
      }  
    }else{
      $data['filter_status'] = '*';
    }

    if(!empty($data['filter_product_code'])){
      $filter_product_code = trim($data['filter_product_code']);
      $filter['rd.product_code'] = $filter_product_code;
    }

    /*
     * 强制添加仓库筛选功能
     * @author sonicsjh
     */
    $data['warehouseLocked'] = false;
    if ($this->user->getLP() > 0) {
        $data['warehouseLocked'] = true;
        $filter['w.warehouse_id'] = $this->user->getLP();
    }

    if(!empty($data['filter_product_name'])){
      
      $data['filter_product_name'] = trim($data['filter_product_name']);
   	
    }

	//获取数据

    $stocl_list =  $this->model_stock_stock_in->getList($page, $filter);
    
    foreach ($stocl_list as $key => $value) {
    	if ($value['status']!=2) {
    		$stocl_list[$key]['all_color']='red';
    	}
    }
    $data['Warehouse_name'] = $this->model_stock_stock_in->getWarehouse();
   	$data['Warehouse_name'][] = array('warehouse_id'=>'*','name'=>'全部');
    $data['refer_type'] = $this->model_stock_stock_in->referType();
   	$data['refer_type'][] = array('refer_type_id'=>'*','name'=>'全部');
    $data['status_array'] = $this->model_stock_stock_in->getstatus();

   	$data['status_array'][] = array('id'=>'*','name'=>'全部');
    $order_total = $this->model_stock_stock_in->getListCount($filter);
  	$order_total =count($order_total);
    $pagination = new Pagination();
    $pagination->total = $order_total;
    $pagination->page = $page;
    $pagination->limit = $this->config->get('config_limit_admin');
    $pagination->url = $this->url->link('stock/stock_in', 'token=' . $this->session->data['token'] . '&page={page}'.'&filter_date_end='.$filter_date_end.'&filter_date_start='.$filter_date_start.'&refer_type_id='.$data['refer_type_id'].'&filter_status='.$data['filter_status'].'&warehouse_id='.$data['warehouse_id'].'&username='.$data['username'].'&in_id='.$data['in_id'].'&filter_product_code='.$data['filter_product_code'].'&filter_product_name='.$data['filter_product_name'], 'SSL');

    $data['pagination'] = $pagination->render();
    $data['stocl_list'] = $stocl_list;
	$data['results'] = sprintf($this->language->get('text_pagination'), ($order_total) ? (($page - 1) * $this->config->get('config_limit_admin')) + 1 : 0, ((($page - 1) * $this->config->get('config_limit_admin')) > ($order_total - $this->config->get('config_limit_admin'))) ? $order_total : ((($page - 1) * $this->config->get('config_limit_admin')) + $this->config->get('config_limit_admin')), $order_total, ceil($order_total / $this->config->get('config_limit_admin')));


		/*面包屑导航栏*/
		$data['heading_title'] = $this->language->get('heading_title');
		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_home'),
			'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
		);
		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('heading_title'),
			'href' => $this->url->link('stock/stock_in', 'token=' . $this->session->data['token'] . $url, 'SSL')
		);
		/*面包屑导航栏*/
		
		/*右上操作按钮*/

		$data['button_add'] = $this->language->get('button_add');
		$data['buttons_enable'] = $this->language->get('buttons_enable');
		$data['buttons_disable'] = $this->language->get('buttons_disable');
		$data['text_confirm_enable'] = $this->language->get('text_confirm_enable');
		$data['text_confirm_disable'] = $this->language->get('text_confirm_disable');
		
		$data['add'] = $this->url->link('stock/stock_in/add', 'token=' . $this->session->data['token'] . $url, 'SSL');
		$data['enable_action'] = $this->url->link('stock/stock_in/enableStatus', 'token=' . $this->session->data['token'] . $url, 'SSL');
		$data['disable_action'] = $this->url->link('stock/stock_in/disableStatus', 'token=' . $this->session->data['token'] . $url, 'SSL');
		/*右上操作按钮*/
		

		/*标题*/
		$data['text_list'] = $this->language->get('text_list');
		/*标题*/
		    // var_dump($data['refer_type_id']);
		//加载头部侧边栏底部
		$data['header'] = $this->load->controller('common/header');
		$data['column_left'] = $this->load->controller('common/column_left');
		$data['footer'] = $this->load->controller('common/footer');
		$this->response->setOutput($this->load->view('stock/stock_in_list.tpl', $data));

	}

	public function view(){
		$this->load->language('stock/stock_in');
		// var_dump($this->language->get('heading_title'));die();


		$this->document->setTitle($this->language->get('heading_title'));
		
		$this->load->model('stock/stock_in');
		$url = '';
    	$data = I('get.');
    	// var_dump($data);
    	$stock_list =  $this->model_stock_stock_in->getstock($data['stock_id']);
    	// var_dump($stock_list);
    	$stockHistory =  $this->model_stock_stock_in->getstockHistory($data['stock_id']);
    	$data['histories']=$stockHistory;
		$data['stock_list'] = $stock_list;
		/*面包屑导航栏*/
		$data['heading_title'] = '入库单';
		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_home'),
			'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
		);
		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('heading_title'),
			'href' => $this->url->link('stock/stock_in', 'token=' . $this->session->data['token'] . $url, 'SSL')
		);
		/*面包屑导航栏*/
		
		/*右上操作按钮*/
		$data['button_add'] = $this->language->get('button_add');
		$data['buttons_enable'] = $this->language->get('buttons_enable');
		$data['buttons_disable'] = $this->language->get('buttons_disable');
		$data['text_confirm_enable'] = $this->language->get('text_confirm_enable');
		$data['text_confirm_disable'] = $this->language->get('text_confirm_disable');
		$data['cancel'] = $this->url->link('stock/stock_in', 'token=' . $this->session->data['token'] , 'SSL');
		$data['add'] = $this->url->link('stock/stock_in/add', 'token=' . $this->session->data['token'] . $url, 'SSL');
		$data['enable_action'] = $this->url->link('stock/stock_in/enableStatus', 'token=' . $this->session->data['token'] . $url, 'SSL');
		$data['disable_action'] = $this->url->link('stock/stock_in/disableStatus', 'token=' . $this->session->data['token'] . $url, 'SSL');
		/*右上操作按钮*/
		
		/*标题*/
		$data['text_list'] = $this->language->get('text_list');
		/*标题*/
		
		//加载头部侧边栏底部
		$data['header'] = $this->load->controller('common/header');
		$data['column_left'] = $this->load->controller('common/column_left');
		$data['footer'] = $this->load->controller('common/footer');
    	$this->response->setOutput($this->load->view('stock/stock_in_list_view.tpl', $data));
	}

	public function addo() {
		$this->document->setTitle('新增入库单');
		$this->load->model('stock/stock_in');
		$this->form();
	}

	public function add() {
		$this->load->model('stock/stock_in');
	    $this->document->addScript('view/javascript/angular.js');
	    $this->document->addScript('view/javascript/stock.js');
	    $this->getForm();
	}
	
	protected function form(){
		$data['breadcrumbs'] = array();

		$data['breadcrumbs'][] = array(
		  'text' => $this->language->get('text_home'),
		  'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
		);

		$data['breadcrumbs'][] = array(
		  'text' => '入库单',
		  'href' => $this->url->link('stock/stock_in', 'token=' . $this->session->data['token'] , 'SSL')
		);
		$this->document->addScript('view/javascript/angular.js');
    	$this->document->addScript('view/javascript/bhz_ctl.js');

		$data['token'] = $this->session->data['token'];


		if (isset($this->session->data['error'])) {
		  $data['error_warning'] = $this->session->data['error'];

		  unset($this->session->data['error']);
		} elseif (isset($this->error['warning'])) {
		  $data['error_warning'] = $this->error['warning'];
		} else {
		  $data['error_warning'] = '';
		}

		if (isset($this->session->data['success'])) {
		  $data['success'] = $this->session->data['success'];

		  unset($this->session->data['success']);
		} else {
		  $data['success'] = '';
		}
		$data['refer_type'] = array('2' =>'采购单','3' =>'退货单' );
    	$warehouse = $this->model_stock_stock_in->getWarehouse();
    	$data['warehouse'] =$warehouse;
    			$json = array();
		$arg = I('get.');
		if(!empty($arg['bill'])){
			$bill = trim($arg['bill']);
	    }
		if(!empty($arg['refer_type'])){
			$refer_type = trim($arg['refer_type']);
			if ($refer_type==2) {
				$product = $this->model_stock_stock_in->searchPo($bill);
			}elseif ($refer_type==3) {
				$product = $this->model_stock_stock_in->searchSo($bill);
			}
		}
		if ($product) {
			$data['po_products'] = $product;
		}
		$data['po_id'] = $bill;

		$data['header'] = $this->load->controller('common/header');
		$data['column_left'] = $this->load->controller('common/column_left');
		$data['footer'] = $this->load->controller('common/footer');

		$this->response->setOutput($this->load->view('stock/stock_in_list_add.tpl', $data));
	}


	protected function getForm(){
		$data['breadcrumbs'] = array();

		$data['breadcrumbs'][] = array(
		  'text' => $this->language->get('text_home'),
		  'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
		);

		$data['breadcrumbs'][] = array(
		  'text' => '入库单',
		  'href' => $this->url->link('stock/stock_in', 'token=' . $this->session->data['token'] , 'SSL')
		);
		$this->document->addScript('view/javascript/angular.js');
    	$this->document->addScript('view/javascript/stock.js');
		$data['heading_title'] = '入库单';

		$data['token'] = $this->session->data['token'];


		if (isset($this->session->data['error'])) {
		  $data['error_warning'] = $this->session->data['error'];

		  unset($this->session->data['error']);
		} elseif (isset($this->error['warning'])) {
		  $data['error_warning'] = $this->error['warning'];
		} else {
		  $data['error_warning'] = '';
		}

		if (isset($this->session->data['success'])) {
		  $data['success'] = $this->session->data['success'];

		  unset($this->session->data['success']);
		} else {
		  $data['success'] = '';
		}
		$data['cancel'] = $this->url->link('stock/stock_in', 'token=' . $this->session->data['token'] , 'SSL');

		$data['refer_type'] = $this->model_stock_stock_in->referType();
		$data['status'] = $this->model_stock_stock_in->getstatus();;
    	$warehouse = $this->model_stock_stock_in->getWarehouse();
    	$data['warehouse'] =$warehouse;
    	// var_dump($data);
		$data['header'] = $this->load->controller('common/header');
		$data['column_left'] = $this->load->controller('common/column_left');
		$data['footer'] = $this->load->controller('common/footer');
    	$this->response->setOutput($this->load->view('stock/stock_in_list_addnow.tpl', $data));
	}

	public function edit() {
		$this->document->addScript('view/javascript/angular.js');
    	$this->document->addScript('view/javascript/stock.js');
		$data['token'] = $this->session->data['token'];
		$this->load->model('stock/stock_in');
		$url = '';
    	$data = I('get.');
    	// var_dump($data);
    	$stock_list =  $this->model_stock_stock_in->getstock($data['stock_id']);
    	$stockHistory =  $this->model_stock_stock_in->getstockHistory($data['stock_id']);
    	$data['histories']=$stockHistory;
		$data['stock_list'] = $stock_list;
		/*面包屑导航栏*/
		$data['heading_title'] = '入库单';
		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_home'),
			'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
		);
		$data['breadcrumbs'][] = array(
			'text' => '入库单',
			'href' => $this->url->link('stock/stock_in', 'token=' . $this->session->data['token'] . $url, 'SSL')
		);

		$data['cancel'] = $this->url->link('stock/stock_in', 'token=' . $this->session->data['token'] , 'SSL');
		$data['header'] = $this->load->controller('common/header');
		$data['column_left'] = $this->load->controller('common/column_left');
		$data['footer'] = $this->load->controller('common/footer');

		$this->response->setOutput($this->load->view('stock/stock_in_list_edit.tpl', $data));
	}


	public function save()
	{
		$this->load->model('stock/stock_in');
		$data = json_decode(file_get_contents('php://input'), true);
		$filter = C('DEFAULT_FILTER');
		$data   =   is_array($data) ? array_map_recursive($filter,$data) : $filter($data);
		$json = array();
		//相关单据号、状态、相关单据类型、入库仓库是否为空
		if(!isset($json['error'])) {
		$empty_check = array('refer_id'=>'相关单据号', 'refer_type'=>'相关单据类型', 'warehouse'=>'入库仓库');
		foreach ($empty_check as $key => $msg) {
			  if(empty($data[$key])) {
			    $json['error'] = '请输入' . $msg;
			  }
			}  
		}

    	

		if(!isset($json['error'])) {
			$stock =  $this->model_stock_stock_in->addstock($data);
			$comments = "增加入库单" ; 
      		$this->model_stock_stock_in->addStHistory($stock, $this->user->getId(),$comments);
            /*
             * 手工创建完成状态入库单时，调整库存
             * @author sonicsjh
             */
            if (2 == $data['status']) {
                $this->model_stock_stock_in->addInventory($data['warehouse'],$data,$data['refer_type'],$stock);
            }
			$json['success'] = true;
		} else {
			$json['success'] = false;
		}

		 $this->response->addHeader('Content-Type: application/json');
		 $this->response->setOutput(json_encode($json));
		return;
    
	}

	public function savedit()
	{
		$this->load->model('stock/stock_in');
		$data = json_decode(file_get_contents('php://input'), true);
		$filter = C('DEFAULT_FILTER');
		$data   =   is_array($data) ? array_map_recursive($filter,$data) : $filter($data);
		$json = array();
    	$stock =  $this->model_stock_stock_in->editstock($data);
    	$comments = $stock ; 
      	$this->model_stock_stock_in->addStHistory($data['in_id'], $this->user->getId(),$comments);
		if(!isset($json['error'])) {
			$json['success'] = true;
		} else {
			$json['success'] = false;
		}

		 $this->response->addHeader('Content-Type: application/json');
		 $this->response->setOutput(json_encode($json));
		return;
    
	}


	public function savestock()
	{
		$this->load->model('stock/stock_in');
		$data = json_decode(file_get_contents('php://input'), true);
		$filter = C('DEFAULT_FILTER');
		$data   =   is_array($data) ? array_map_recursive($filter,$data) : $filter($data);
		$json = array();
    	$status =  $this->model_stock_stock_in->getStatusById($data);
    	// var_dump($status);die();
    	if ($status ==1) {
			$warehouse_id = I('get.warehouse_id');
	    	$refer_type_id = I('get.refer_type_id');
	    	$flog =  $this->model_stock_stock_in->savestock($data);
	    	if ($flog) {
	    		$comments = $flog ; 

	      		$this->model_stock_stock_in->addStHistory($data['in_id'], $this->user->getId(),$comments);
	    	}
			 $this->model_stock_stock_in->addInventory($warehouse_id,$data,$refer_type_id,$data['in_id']);
	    	$comments = "完成入库单" ; 
	      	$this->model_stock_stock_in->addStHistory($data['in_id'], $this->user->getId(),$comments);
	      	//生成应付单据
	      	if ($refer_type_id==2) {
	      		$stockm = $this->model_stock_stock_in->getStockM($data['in_id']);
	      		$money_in = $this->model_stock_stock_in->getMoney($stockm['refer_id']);
	      		if (empty($money_in)) {
					$res1 = $this->model_stock_stock_in->getMomessage($data['in_id']);
					// var_dump($res1);die();
			 	 	$this->model_stock_stock_in->addMoneyOutP($res1);
	      		}else{
	      			// var_dump($money_in);die();
	      			$this->model_stock_stock_in->editMoney($money_in,$stockm,$data['in_id']);
	      			$comments = '修改应付金额：增加'.$stockm['buy_money'];
	      			$this->model_stock_stock_in->addMoHistory($money_in['money_out_id'], $this->user->getId(),$comments);
	      		}
			 	
			 }
			 if ($refer_type_id==3) {
			 	$resul = $this->model_stock_stock_in->getMomessageRo($data['in_id']);
			 	$this->model_stock_stock_in->addMoneyOutRo($resul);
			 }
    	}
 
		if(!isset($json['error'])) {
			$json['success'] = true;
		} else {
			$json['success'] = false;
		}

		 $this->response->addHeader('Content-Type: application/json');
		 $this->response->setOutput(json_encode($json));
		return;
    
	}


	public function cancel()
	{
		$this->load->model('stock/stock_in');
		$json = array();
    	$data = I('get.');
    	if (empty($data['in_id'])) {
	    	$json['error'] = '参数缺失';
    	}else{
 			if ($this->model_stock_stock_in->cancel($data['in_id'])) {
 				$comments = "作废入库单" ; 
      			$this->model_stock_stock_in->addStHistory($data['in_id'], $this->user->getId(),$comments);
 				$json['success'] = '作废成功';
 			}else{
 				$json['success'] = '作废失败';
 			}
	    	
	    }

	    $this->response->addHeader('Content-Type: application/json');
	    $this->response->setOutput(json_encode($json));
    
	}

	public function recover()
	{
		$this->load->model('stock/stock_in');
		$json = array();
    	$data = I('get.');
    	if (empty($data['in_id'])) {
	    	$json['error'] = '参数缺失';
    	}else{
 			if ($this->model_stock_stock_in->recover($data['in_id'])) {
 				$comments = "取消作废入库单" ; 
      			$this->model_stock_stock_in->addStHistory($data['in_id'], $this->user->getId(),$comments);
 				$json['success'] = '取消作废成功';
 			}else{
 				$json['success'] = '取消作废失败';
 			}
	    	
	    }

	    $this->response->addHeader('Content-Type: application/json');
	    $this->response->setOutput(json_encode($json));
    
	}

	public function product()
	{
		$json = array();
		$this->load->model('stock/stock_in');
    	$data = I('get.');
    	$json =  $this->model_stock_stock_in->getproduct($data);
	    $this->response->addHeader('Content-Type: application/json');
	    $this->response->setOutput(json_encode($json));
	}

	public function exportLists(){
		$this->load->model('stock/stock_in');
	    if($this->user->getLp()){
	      $filter['stock_in.user_id'] = $this->user->getId();
	    }
	    $data = I('get.');
	    // var_dump($data);
	    $this->document->addScript('view/javascript/angular.js');
	    $this->document->addScript('view/javascript/bhz_ctl.js');
	    if(!empty($data['filter_date_start'])){
	      $filter_date_start = $data['filter_date_start'];
	    }else{
	      $filter_date_start = '0000-00-00';
	    }

	    if(!empty($data['filter_date_end'])){
	      $filter_date_end = $data['filter_date_end'];
	    }else{
	      $filter_date_end = '9999-12-31';
	    }

	    $filter['stock_in.date_added'] = array('between',array($filter_date_start.' 00:00:00',$filter_date_end.' 23:59:59'));

	    if(isset($data['warehouse_id'])){
	      $warehouse_id = trim($data['warehouse_id']);
	      if($warehouse_id!='*'){
	      	$filter['w.warehouse_id'] = $warehouse_id;
	      }  
	    }else{
	      $data['warehouse_id'] = '*';
	    }

	    if(isset($data['refer_type_id'])){
	      $refer_type_id = trim($data['refer_type_id']);
	      if($refer_type_id!='*'){
	      	$filter['stock_in.refer_type_id'] = $refer_type_id;
	      }  
	    }else{
	      $data['refer_type_id'] = '*';
	    }

	    if(!empty($data['username'])){
	      $username = trim($data['username']);
	      $filter['v.username'] = array('like',"%".$username."%");
	    }

	    if(isset($data['filter_status'])){
	      $filter_status = trim($data['filter_status']);
	      if($filter_status!='*'){
	        $filter['stock_in.status'] = $filter_status;
	      }  
	    }else{
	      $data['filter_status'] = '*';
	    }

	    if(!empty($data['filter_product_code'])){
	      $filter_product_code = trim($data['filter_product_code']);
	      $filter['rd.product_code'] = $filter_product_code;
	    }

	    if(!empty($data['filter_product_name'])){
	      
	      $data['filter_product_name'] = trim($data['filter_product_name']);
	   	
	    }

		//获取数据

	    $stocl_list =  $this->model_stock_stock_in->getAllList($filter);

	    foreach ($stocl_list as $key => $value) {
	      $save_data[] = array(
	        'in_id'          =>  $value['in_id'],
	        'refer_type'   =>  $value['refer_type'],
	        'refer_id'           =>  $value['refer_id'],
	        'warehouse_name'         =>  $value['warehouse_name'],
	        'username'    =>  $value['username'],
	        'buy_money' =>  $value['buy_money'],
	        'status_name'    =>  $value['status_name'],
	        'in_date'            =>  $value['in_date'],
	        'date_added'    =>  $value['date_added']
	        );
	    }

	    $this->load->library('PHPExcel/PHPExcel');
	    $objPHPExcel = new PHPExcel();    
	    $objProps = $objPHPExcel->getProperties();    
	    $objProps->setCreator("Think-tec");
	    $objProps->setLastModifiedBy("Think-tec");    
	    $objProps->setTitle("Think-tec Contact");    
	    $objProps->setSubject("Think-tec Contact Data");    
	    $objProps->setDescription("Think-tec Contact Data");    
	    $objProps->setKeywords("Think-tec Contact");    
	    $objProps->setCategory("Think-tec");
	    $objPHPExcel->setActiveSheetIndex(0);     
	    $objActSheet = $objPHPExcel->getActiveSheet(); 
	       
	    $objActSheet->setTitle('Sheet1');
	    $col_idx = 'A';
	    $headers = array( '入库单号','相关单据类型','相关单据号', '入库仓库','操作人','本单据采购总金额','单据状态','入库时间', '创建时间');
	    $row_keys = array('in_id','refer_type','refer_id','warehouse_name','username','buy_money','status_name','in_date',   'date_added',);
	    foreach ($headers as $header) {
	      $objActSheet->setCellValue($col_idx++.'1', $header);  
	    }
	    //添加物流信息
	    $i = 2;
	    foreach ($save_data as $rlst) {
	      $col_idx = 'A';
	      foreach ($row_keys as $rk) {
	        // $objActSheet->setCellValue($col_idx++.$i, $rlst[$rk]); 
	        $objActSheet->setCellValueExplicit($col_idx++.$i, $rlst[$rk], PHPExcel_Cell_DataType::TYPE_STRING);
	      }
	      $i++;
	    } 

	    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
	    
	    ob_end_clean();
	    // Redirect output to a client’s web browser (Excel2007)
	    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
	    header('Content-Disposition: attachment;filename="stock_in_'.date('Y-m-d',time()).'.xlsx"');
	    header('Cache-Control: max-age=0');
	    // If you're serving to IE 9, then the following may be needed
	    header('Cache-Control: max-age=1');

	    // If you're serving to IE over SSL, then the following may be needed
	    header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
	    header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
	    header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
	    header ('Pragma: public'); // HTTP/1.0
	    $objWriter->save('php://output'); 
	    exit;
  	}
  	

  	public function exportStock(){
		$this->load->model('stock/stock_in');
	    if($this->user->getLp()){
	      $filter['stock_in.user_id'] = $this->user->getId();
	    }
	    $data = I('get.');
	    // var_dump($data);
	    $this->document->addScript('view/javascript/angular.js');
	    $this->document->addScript('view/javascript/bhz_ctl.js');
	    if(!empty($data['filter_date_start'])){
	      $filter_date_start = $data['filter_date_start'];
	    }else{
	      $filter_date_start = '0000-00-00';
	    }

	    if(!empty($data['filter_date_end'])){
	      $filter_date_end = $data['filter_date_end'];
	    }else{
	      $filter_date_end = '9999-12-31';
	    }

	    $filter['stock_in.date_added'] = array('between',array($filter_date_start.' 00:00:00',$filter_date_end.' 23:59:59'));

	    if(isset($data['warehouse_id'])){
	      $warehouse_id = trim($data['warehouse_id']);
	      if($warehouse_id!='*'){
	      	$filter['w.warehouse_id'] = $warehouse_id;
	      }  
	    }else{
	      $data['warehouse_id'] = '*';
	    }

	    if(isset($data['refer_type_id'])){
	      $refer_type_id = trim($data['refer_type_id']);
	      if($refer_type_id!='*'){
	      	$filter['stock_in.refer_type_id'] = $refer_type_id;
	      }  
	    }else{
	      $data['refer_type_id'] = '*';
	    }

	    if(!empty($data['username'])){
	      $username = trim($data['username']);
	      $filter['v.username'] = array('like',"%".$username."%");
	    }

	    if(isset($data['filter_status'])){
	      $filter_status = trim($data['filter_status']);
	      if($filter_status!='*'){
	        $filter['stock_in.status'] = $filter_status;
	      }  
	    }else{
	      $data['filter_status'] = '*';
	    }

	    if(!empty($data['filter_product_code'])){
	      $filter_product_code = trim($data['filter_product_code']);
	      $filter['rd.product_code'] = $filter_product_code;
	    }

	    if(!empty($data['filter_product_name'])){
	      
	      $data['filter_product_name'] = trim($data['filter_product_name']);
	   	
	    }

		//获取数据

	    $stocl_list =  $this->model_stock_stock_in->getAllDetaill($filter);
	    foreach ($stocl_list as $key => $value) {
	      $save_data[] = array(
	        'in_id'          =>  $value['in_id'],
	        'refer_type'   =>  $value['refer_type'],
	        'refer_id'           =>  $value['refer_id'],
	        'vendor_name'           =>  $value['vendor_name'],
	        'warehouse_name'         =>  $value['warehouse_name'],
	        'username'    =>  $value['username'],
	        'buy_money' =>  $value['buy_money'],
	        'status_name'    =>  $value['status_name'],
	        'in_date'            =>  $value['in_date'],
	        'pname'    =>  $value['pname'],
	        'ean'    =>  $value['ean'],
	        'product_code'    =>  $value['product_code'],
	        'product_quantity'    =>  $value['product_quantity'],
	        'products_money'    =>  $value['products_money'],
	        'product_price'    =>  $value['product_price'],
	        'comment'    =>  $value['comment'],
	        );
	    }

	    $this->load->library('PHPExcel/PHPExcel');
	    $objPHPExcel = new PHPExcel();    
	    $objProps = $objPHPExcel->getProperties();    
	    $objProps->setCreator("Think-tec");
	    $objProps->setLastModifiedBy("Think-tec");    
	    $objProps->setTitle("Think-tec Contact");    
	    $objProps->setSubject("Think-tec Contact Data");    
	    $objProps->setDescription("Think-tec Contact Data");    
	    $objProps->setKeywords("Think-tec Contact");    
	    $objProps->setCategory("Think-tec");
	    $objPHPExcel->setActiveSheetIndex(0);     
	    $objActSheet = $objPHPExcel->getActiveSheet(); 
	       
	    $objActSheet->setTitle('Sheet1');
	    $col_idx = 'A';
	    $headers = array( '入库单号','相关单据类型','相关单据号','供应商名称' ,'入库仓库','操作人','本单据采购总金额','单据状态','入库时间', '创建时间','商品名称','商品编码','箱入数','商品数量','商品进价','商品总额','备注');
	    $row_keys = array('in_id','refer_type','refer_id','vendor_name','warehouse_name','username','buy_money','status_name','in_date',   'date_added','pname','product_code','ean','product_quantity','product_price','products_money','comment');
	    foreach ($headers as $header) {
	      $objActSheet->setCellValue($col_idx++.'1', $header);  
	    }
	    //添加物流信息
	    $i = 2;
	    foreach ($save_data as $rlst) {
	      $col_idx = 'A';
	      foreach ($row_keys as $rk) {
	        // $objActSheet->setCellValue($col_idx++.$i, $rlst[$rk]); 
	        $objActSheet->setCellValueExplicit($col_idx++.$i, $rlst[$rk], PHPExcel_Cell_DataType::TYPE_STRING);
	      }
	      $i++;
	    } 

	    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
	    
	    ob_end_clean();
	    // Redirect output to a client’s web browser (Excel2007)
	    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
	    header('Content-Disposition: attachment;filename="stock_in_'.date('Y-m-d',time()).'.xlsx"');
	    header('Cache-Control: max-age=0');
	    // If you're serving to IE 9, then the following may be needed
	    header('Cache-Control: max-age=1');

	    // If you're serving to IE over SSL, then the following may be needed
	    header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
	    header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
	    header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
	    header ('Pragma: public'); // HTTP/1.0
	    $objWriter->save('php://output'); 
	    exit;
  	}
  	public function export(){
	    $in_id = I('get.in_id');
	    if(!$in_id){
	      $in_id = 0;
	    }
		$this->load->model('stock/stock_in');
	    $stock = $this->model_stock_stock_in->getstock($in_id);
	    // var_dump($stock);
	    $data['stock'] = $stock;
	    if(!$po){
	      $this->load->language('error/not_found');
	 
	      $this->document->setTitle($this->language->get('heading_title'));

	      $data['heading_title'] = $this->language->get('heading_title');
	 
	      $data['text_not_found'] = $this->language->get('text_not_found');
	 
	      $data['breadcrumbs'] = array();

	      $data['breadcrumbs'][] = array(
	        'text' => $this->language->get('heading_title'),
	        'href' => $this->url->link('error/not_found', 'token=' . $this->session->data['token'], 'SSL')
	      );
	 

	      $data['footer'] = $this->load->controller('common/footer');
	 
	      $this->response->setOutput($this->load->view('error/not_found.tpl', $data));
	    }
	    // $po_products = $this->model_sale_purchase_order->getPoProducts($in_id);
	    // $data['po_products'] = $po_products;

	    $this->load->library('PHPExcel/PHPExcel');
	    $objReader = PHPExcel_IOFactory::createReader('Excel5');
	    $objPHPExcel = $objReader->load(DIR_SYSTEM . "template/stock_tpl.xls"); 
	    // var_dump(DIR_SYSTEM);die();
	    $objPHPExcel->getProperties()->setCreator("Think-tec")
	               ->setLastModifiedBy("Think-tec")
	               ->setTitle("Bai Huo Zhan PO")
	               ->setSubject("Bai Huo Zhan PO")
	               ->setDescription("Bai Huo Zhan PO")
	               ->setKeywords("Bai Huo Zhan, Think-tec")
	               ->setCategory("Think-tec");

	    $objPHPExcel->setActiveSheetIndex(0);
	    $objActSheet = $objPHPExcel->getActiveSheet();
	    // var_dump($stock);die();
	    $objActSheet->setCellValue('B2', $stock['in_id']);
	    $objPHPExcel->getActiveSheet()->getStyle('B2')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
	    $objActSheet->setCellValue('E2', $stock['date_added']);
	    $objActSheet->setCellValue('B3', $stock['refer_id']);
	    $objActSheet->setCellValue('B4', $stock['warehouse_name']);
	    $objActSheet->setCellValue('B5', $stock['username']);
	    $objActSheet->setCellValue('E4', $stock['status_name']);
	    $objActSheet->setCellValue('E3', $stock['refer_type']);
	    $row_num = 7;
	    $styleBorderOutline = array(
	      'borders' => array(
	        'outline' => array(
	          'style' => PHPExcel_Style_Border::BORDER_THIN,
	        ),
	      ),
	    );
	    // var_dump($styleBorderOutline);die();
	    $objPHPExcel->getActiveSheet()->insertNewRowBefore(8, count($stock['product']));
	    $count = 0;
	    foreach ($stock['product'] as $key => $value) {
	      $row_num++;
	      $objActSheet->setCellValue('A'.$row_num, $row_num-7);
	      $objActSheet->setCellValue('B'.$row_num, $value['name']);
	      $objActSheet->setCellValueExplicit('C'.$row_num, $value['sku'],PHPExcel_Cell_DataType::TYPE_STRING);
	      $objActSheet->setCellValue('D'.$row_num, $value['position1']);
	      $objActSheet->setCellValue('E'.$row_num, $value['position2']);
	      $objActSheet->setCellValue('F'.$row_num, $value['product_quantity']);
	      $objActSheet->setCellValue('G'.$row_num, $value['product_code'],PHPExcel_Cell_DataType::TYPE_STRING);
	      // $objActSheet->setCellValue('J'.$row_num, $value['products_money']);
	      $objPHPExcel->getActiveSheet()->getStyle('A'.$row_num)->applyFromArray($styleBorderOutline);
	      $objPHPExcel->getActiveSheet()->getStyle('B'.$row_num)->applyFromArray($styleBorderOutline);
	      $objPHPExcel->getActiveSheet()->getStyle('C'.$row_num)->applyFromArray($styleBorderOutline);
	      $objPHPExcel->getActiveSheet()->getStyle('D'.$row_num)->applyFromArray($styleBorderOutline);
	      $objPHPExcel->getActiveSheet()->getStyle('E'.$row_num)->applyFromArray($styleBorderOutline);
	      $objPHPExcel->getActiveSheet()->getStyle('F'.$row_num)->applyFromArray($styleBorderOutline);
	      $objPHPExcel->getActiveSheet()->getStyle('G'.$row_num)->applyFromArray($styleBorderOutline);
	    }
	    $row_num++;

	    // $objActSheet->setCellValue('F'.$row_num, $stock['buy_money']);
	    // $row_num++;
	    // $objActSheet->setCellValue('F'.$row_num, date('Y-m-d', strtotime($stock['buy_money'])));

	    // $objPHPExcel->getActiveSheet()->getStyle('A7:G'.$row_num)->getFont()->setSize(12);
	    
	    $objActSheet->setTitle('入库单');

	    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
	    ob_end_clean();
	    // Redirect output to a client’s web browser (Excel2007)
	    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
	    header('Content-Disposition: attachment;filename="STOCK_BHZ_'.date('Y-m-d-H-i',time()).'.xlsx"');
	    header('Cache-Control: max-age=0');
	    // If you're serving to IE 9, then the following may be needed
	    header('Cache-Control: max-age=1');
	    // If you're serving to IE over SSL, then the following may be needed
	    header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
	    header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
	    header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
	    header ('Pragma: public'); // HTTP/1.0
	    $objWriter->save('php://output'); 
	    exit;
  }
  public function products(){
    $json = array();

    if (isset($this->request->get['filter_name']) || isset($this->request->get['filter_model'])) {
      $this->load->model('catalog/product');
      $this->load->model('catalog/option');
      $this->load->model('sale/purchase_order');

      

      if (isset($this->request->get['filter_name'])) { //复合查询
        $where['pd.name'] = array('like', '%'.$this->request->get['filter_name'].'%');
		$where['pov.product_code'] = array('like', '%'.$this->request->get['filter_name'].'%');
		$where['_logic'] = 'or';
		$filter['_complex'] = $where;
      }
      $results = $this->model_sale_purchase_order->getProducts($filter);

      foreach ($results as $result) {
        $option_data = array();

        $product_options = $this->model_catalog_product->getProductOptions($result['product_id']);

        foreach ($product_options as $product_option) {
          $option_info = $this->model_catalog_option->getOption($product_option['option_id']);

          if ($option_info) {
            $product_option_value_data = array();

            foreach ($product_option['product_option_value'] as $product_option_value) {
              $option_value_info = $this->model_catalog_option->getOptionValue($product_option_value['option_value_id']);

              if ($option_value_info) {
                $product_option_value_data[] = array(
                  'product_option_value_id' => $product_option_value['product_option_value_id'],
				  'product_code' => $product_option_value['product_code'],
                  'option_value_id'         => $product_option_value['option_value_id'],
                  'name'                    => $option_value_info['name'],
                  'price'                   => (float)$product_option_value['price'], 
                  'price_prefix'            => $product_option_value['price_prefix']
                );
              }
            }

            $option_data[] = array(
              'product_option_id'    => $product_option['product_option_id'],
              'product_option_value' => $product_option_value_data,
              'option_id'            => $product_option['option_id'],
              'name'                 => $option_info['name'],
              'type'                 => $option_info['type'],
              'value'                => $product_option['value'],
              'required'             => $product_option['required']
            );
          }
        }

        $json[] = array(
          'product_id' => $result['product_id'],
          'name'       => strip_tags(html_entity_decode($result['name'], ENT_QUOTES, 'UTF-8')),
          'model'      => $result['model'],
          'product_price'          => $result['product_cost'],
          'sku'         =>$result['sku'],
          'oname'         =>$option_value_info['name'],
          'option'     => $option_data,
          'price'      => $result['price'],
          'packing_no' => $result['packing_no'],
          'product_code' => $result['vproduct_code']
        );
      }
    }
    $this->response->addHeader('Content-Type: application/json');
    $this->response->setOutput(json_encode($json));
  }
  
  public function updelivery_cycle(){
  	 $sql = "SELECT stock_in.refer_id, stock_in.in_id, stock_in.date_added AS 'stime', po.date_added AS 'ptime'FROM stock_in LEFT JOIN po ON stock_in.refer_id = po.id WHERE stock_in.refer_type_id = 2"; 
		$query = $this->db->query($sql);
		$data = $query->rows;
		foreach ($data as $key => $value) {
			if (!empty(strtotime($value['stime']))&&!empty(strtotime($value['stime']))) {
				$time = max(0,(int)(strtotime($value['stime'])-(int)strtotime($value['ptime'])));
				$sql="update stock_in set delivery_cycle=".$time." where in_id =".$value['in_id'];
				// echo $sql;die();
				$this->db->query($sql);
				$sql="update stock_in_detail set delivery_cycle=".$time." where in_id =".$value['in_id'];
				$this->db->query($sql);
			}
			
		}

  }
}
?>